package lol.clann.minecraft.springboot.bukkit.plugin.bukkit;

import lol.clann.minecraft.springboot.bukkit.plugin.Adapter;
import lol.clann.minecraft.springboot.bukkit.plugin.AdapterContext;
import lol.clann.minecraft.springboot.bukkit.plugin.GlobalEventBus;
import lol.clann.minecraft.springboot.bukkit.utils.BukkitUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;

/**
 *
 * @author pyz
 * @date 2019/4/8 8:28 PM
 */
public class AdapterPlugin extends JavaPlugin {

    public static JavaPlugin plugin;

    public AdapterPlugin() {
        AdapterPlugin.plugin = this;
    }

    @Override
    public void onDisable() {
        GlobalEventBus.fire(new CloseSpringContextRequestEvent());
    }

    @Override
    public void onEnable() {
        Adapter.getLogger().info("SBP将在所有插件加载完成后开始启动...");
        AdapterContext.init();
        Bukkit.getScheduler().runTask(this, () -> {
            try {
                Adapter.start(getFile().getParentFile());
            } catch (Throwable e) {
                e.printStackTrace();
                Adapter.getLogger().error("启动失败,为避免损失,将关闭服务器.");
                Adapter.getLogger().error("详情请查看日志,以下为异常信息摘要.");
                log(e);
                printStartFailMessage();
                Bukkit.shutdown();
            }
        });
    }

    private void log(Throwable e) {
        while (e != null) {
            Adapter.getLogger().error(e.getClass().getName() + ":" + e.getMessage());
            e = e.getCause();
        }
    }

    private void printStartFailMessage() {
        BukkitUtils.printBukkitVersions();
        AdapterContext.printServerContext();
    }
}
